<template>
  <a-modal v-model:open="open" title="新增留言" width="800px" @ok="handleOk" @cancel="handleCancel">
    <a-form ref="formRef" :model="formState" :label-col="{ style: { width: '80px' } }" style="margin-top: 16px">
      <a-form-item label="分类一">
        <a-select
          style="width: 100%"
          v-model:value="formState.label_top"
          placeholder="请选择"
          @change="getSecondLabel"
        >
          <a-select-option v-for="item in firstLabelList" :key="item.value" :value="item.value">{{
            item.label
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="分类二">
        <a-select style="width: 100%" v-model:value="formState.label_second" placeholder="请选择">
          <a-select-option v-for="item in secondLabelList" :key="item.id" :value="item.id">{{
            item.label
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="留言内容" name="question" :rules="[{ required: true, message: '请输入留言内容' }]">
        <a-textarea v-model:value="formState.question" placeholder="请输入" :rows="5"></a-textarea>
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script setup lang="ts">
import { ref } from 'vue'
import { fetchDictionarySelect, fetchDictionarySecondLabel, fetchMessageAdd } from '@/api/message'
import { message } from 'ant-design-vue'

const emits = defineEmits(['refresh'])

const open = ref(false)
const handleOk = () => {
  formRef.value.validate().then(async () => {
    const params = {
      ...formState.value,
      label_top_name: formState.value.label_top ? firstLabelList.value.filter((item) => Number(item.value) === Number(formState.value.label_top))[0].label : '',
      label_second_name: formState.value.label_second ? secondLabelList.value.filter((item) => Number(item.id) === Number(formState.value.label_second))[0].label : ''
    }
    const res = await fetchMessageAdd(params)
    if (res.data.code === '200') {
      message.success('留言成功')
      reset()
      emits('refresh')
      open.value = false
    } else {
      message.error(res.data.message)
    }
  })
}
const handleCancel = () => {
  reset()
  open.value = false
}
const reset = () => {
  Object.keys(formState.value).forEach((key) => {
    formState.value[key] = undefined
  })
}
const openModal = () => {
  if (!firstLabelList.value.length) getFirstLabel()
  open.value = true
}

const formRef = ref()
const formState = ref<any>({
  label_top: undefined,
  label_second: undefined,
  question: undefined
})

const firstLabelList = ref<any[]>([])
const getFirstLabel = async () => {
  const res = await fetchDictionarySelect({ value: 9 })
  firstLabelList.value = res.data.data
}
const secondLabelList = ref<any[]>([])
const getSecondLabel = async () => {
  const res = await fetchDictionarySecondLabel({ value: formState.value.label_top })
  secondLabelList.value = res.data.data
}

defineExpose({ openModal })
</script>

<style scoped lang="scss"></style>
